package com.tyl.xtk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tyl.xtk.beans.po.Permission;
import com.tyl.xtk.beans.po.Role;
import com.tyl.xtk.beans.query.PageQuery;
import com.tyl.xtk.beans.vo.PageResult;
import com.tyl.xtk.beans.vo.Result;
import com.tyl.xtk.config.validation.groups.Insert;
import com.tyl.xtk.config.validation.groups.Update;
import com.tyl.xtk.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.groups.Default;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("role")
@Tag(name = "角色管理")
public class RoleController {

    @Resource
    RoleService roleService;

    @GetMapping("")
    @Operation(summary = "获取角色列表（分页）")
    public PageResult<Role> page(PageQuery pageQuery) {
        IPage<Role> rolePage = roleService.selectPage(pageQuery.toPage());
        return PageResult.success(rolePage);
    }

    @GetMapping("{id}")
    @Operation(summary = "获取角色详情")
    public Result<Role> one(@PathVariable @NotNull Long id) {
        Role role = roleService.selectById(id);
        if (role == null) {
            return Result.fail("角色不存在");
        }
        return Result.success(role);
    }
    
    @GetMapping("{id}/permission")
    @Operation(summary = "获取角色的权限列表")
    public Result<List<Permission>> permissions(@PathVariable @NotNull Long id) {
        Role role = roleService.selectById(id);
        if (role == null) {
            return Result.fail("角色不存在");
        }
        List<Permission> permissions = roleService.selectPermissionListByRoleId(id);
        return Result.success(permissions);
    }

    @PostMapping("")
    @Operation(summary = "创建角色")
    public Result<Role> post(@RequestBody @Validated({Insert.class, Default.class}) Role role) {
        boolean insert = roleService.insert(role);
        if (!insert) {
            return Result.fail("创建角色失败");
        }
        return Result.success(role);
    }

    @PutMapping("")
    @Operation(summary = "更新角色")
    public Result<Role> put(@RequestBody @Validated({Update.class, Default.class}) Role role) {
        boolean update = roleService.update(role);
        if (!update) {
            return Result.fail("更新角色失败");
        }
        return Result.success(role);
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除角色")
    public Result<String> delete(@PathVariable @NotNull Long id) {
        boolean remove = roleService.removeById(id);
        if (!remove) {
            return Result.fail("删除角色失败");
        }
        return Result.success("删除角色成功");
    }
}